<?php

namespace App\Console\Commands;

use App\Services\Base\CacheService;
use App\Services\BlockChainServices;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

//php artisan chain:import ETH
class ChainImport extends Command
{
    protected $chain = 'ETH';
    protected $lower_chain = 'ETH';
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'chain:import {chain}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->chain = $this->argument('chain');
        if (!in_array($this->chain, ['ETH', "TRON", "BSC"])) {
            $this->error("链错误");
            return;
        }

        $this->lower_chain = strtolower($this->chain);
        while (true) {
            try {
                $data = CacheService::rPop("{$this->lower_chain}:transaction");
		        if (!$data) {
                    sleep(3);
                    continue;
                }
                $this->logger()->info("chain:import:" . $data);
                $data = json_decode($data, true);
                if ($data['status'] != 1) {
                    continue;
                }

                if (strlen($data['timestamp']) > 13) {
                    $data['timestamp'] = substr($data['timestamp'], 0, 13);
                }

                $this->logger()->info(json_encode($data));
                BlockChainServices::import($data);
                usleep(5);

            } catch (\Throwable $e) {

                $_log = "$this->chain: {$e->getMessage()} {$e->getFile()}:{$e->getLine()}";
                $this->error($_log);
                $this->logger()->error($_log);
            }
        }

    }

    protected function logger()
    {
        return Log::channel("chain");
    }


}
